<?php

namespace App\Http\Controllers\Knight;

use App\Helper\Functions;
use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\Controller;
use App\Http\Models\Knight;
use App\Http\Models\KnightApply;
use App\Http\Models\AgencyOrder;
use App\Http\Models\AgencyAddress;
use App\Http\Models\AskAddress;
use App\Http\Controllers\Order\UserController as orderIndex;

class IndexController extends Controller
{
	// 检查骑士身份并返回信息
	private function getKnightInfo($uId){
		$Knight = new Knight();
		$knightInfo = $Knight->getInfoByUid($uId);
		if (empty($knightInfo)){
			echo $this->returnMsg(0, '没有骑士权限');
			exit;
		}
		return $knightInfo;
	}

	// 获取报名信息
	public function getApplyInfo(){
		$list = DB::table('knight_level')->get();
		return $this->returnMsg(1, 'OK', $list);
	}

	// 申请骑士
	public function apply(Request $request){

		$token = $request->token;
		$klId = $request->klId;

//		$ksIds = $request->ksIds;
//		if ($klId >= 3){
//			if (empty($ksIds)){
//				return $this->returnMsg(0, '申请该等级骑士需要提交工作时间段');
//			}
//		}

		$userInfo = $this->getUserInfoFromToken($token, true);

		// 获取等级信息
		$levelInfo = DB::table('knight_level')->where('klId', $klId)->first();
		if (empty($levelInfo)){
			return $this->returnMsg(0, '没有该等级信息');
		}

		// 判断是否已经在申请中
		$KnightApply = new KnightApply();
		$applyInfo = $KnightApply->getInfoByUid($userInfo['uCode']);

		if (!empty($applyInfo)){
			if ($applyInfo->kaStatus == 0){
				return $this->returnMsg(0, '上一个申请还在审核中，无法重复申请');
			}

//			if ($applyInfo->kaStatus == 2 || $applyInfo->kaStatus == 1){
////				$checkTime = strtotime ($applyInfo->kaCheckTime); //当前时间  ,注意H 是24小时 h是12小时
//				$checkTime = strtotime ($applyInfo->createTime); //当前时间  ,注意H 是24小时 h是12小时
//				$now = strtotime (date('Y-m-d H:i:s', time()));  //过年时间，不能写2014-1-21 24:00:00  这样不对
//				$hour = 48;
//				$Interval = 60 * 60 * $hour; // 一天
//				if ($now - $checkTime < 60 * 60 * 24){
//					return $this->returnMsg(0, "距离上一次申请还不到{$hour}小时");
//				}
//			}
		}



		// 判断是否重复申请
		$Knight = new Knight();
		$knightInfo = $Knight->getInfoByUid($userInfo['uCode']);

		if (!empty($knightInfo)){
			if ($knightInfo->klId == $klId){
				return $this->returnMsg(0, '你已经是该等级骑士了，不能重复申请');
			}

			if ($knightInfo->klId > $klId){
				return $this->returnMsg(0, '你当前的等级高于申请等级');
			}
		}

		$KnightApply->addInfo($userInfo['uCode'], $userInfo['addition']['uCustomInfo']['csId'], $klId);
//		if (empty($knightInfo)){
//			$Knight->addKnight($userInfo['uCode'], $addressInfo->csId, $klId);
//		}

//		if ($klId >= 3){
//			// 写入工作时间
//			$hourData = $this->setHour($request);
//			$hourData = json_decode($hourData, true);
//			if ($hourData['code'] != 1){
//				return json_encode($hourData);
//			}
//		}

		return $this->returnMsg(1, 'OK');
	}

	// 获取骑士待接任务订单列表
	public function getToDoOrderList($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		// 先获取任务进行中的列表
		$AgencyOrder = new AgencyOrder();
		$doinglist = $AgencyOrder->getKnightDoingList($knightInfo->kId);
		$doinglist = json_decode(json_encode($doinglist), true);

		$assignedList = $AgencyOrder->getKnightAssignedList($knightInfo->kId);
		$assignedList = json_decode(json_encode($assignedList), true);

		$taskList = $AgencyOrder->getTaskList($knightInfo->csId);

		$list = array_merge($doinglist, $assignedList, $taskList);

        $list = $AgencyOrder->doTimeFlag($list);

		return $this->returnMsg(1, 'OK', $list);
	}

    // 获取骑士待接任务订单列表
    public function getToDoOrderSwichList($token){

    	$userInfo = $this->getUserInfoFromToken($token);

    	$knightInfo = $this->getKnightInfo($userInfo['uCode']);

    	// 获取任务进行中的列表
    	$AgencyOrder = new AgencyOrder();
    	$doinglist = $AgencyOrder->getKnightDoingList($knightInfo->kId);
    	$doinglist = json_decode(json_encode($doinglist), true);

    	// $assignedList = $AgencyOrder->getKnightAssignedList($knightInfo->kId);
    	// $assignedList = json_decode(json_encode($assignedList), true);
        $turnList = $AgencyOrder->getOrderToTurnList($knightInfo->csId);
        // 获取已完成列表
        $finishList = $AgencyOrder->getOrderHistory($knightInfo->kId);

        // 获取无人接单列表
    	$taskList = $AgencyOrder->getTaskList($knightInfo->csId);

    	$list['doing'] = $doinglist;
        $list['turn'] = $turnList;
        $list['finish'] = $finishList;
        $list['task'] = $taskList;

    	return $this->returnMsg(1, 'OK', $list);
    }

	// 获取骑士接单历史列表
	public function getOrderHistory($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$AgencyOrder = new AgencyOrder();
		$list = $AgencyOrder->getOrderHistory($knightInfo->kId);

		return $this->returnMsg(1, 'OK', $list);
	}

	// 骑士更改订单状态
	public function knightChangeOrderStatus(Request $request){

		$token = $request->token;
		$aoId = $request->aoId;
		$status = $request->status;

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$AgencyOrder = new AgencyOrder();
		$aoInfo = $AgencyOrder->knightChangeOrderStatus($knightInfo->kId, $aoId, $status);
		if (gettype($aoInfo) == 'string'){
			return $this->returnMsg(0, $aoInfo);
		}

		// 骑士完成订单，增加账户金额
		if ($status == 3){
			$levelInfo = DB::table('knight_level')->where('klId', $knightInfo->klId)->first();
			$scale = (100 - $levelInfo->klFeePercent) / 100;

			// 钱包增加金额
			$walletHost = config('services.extend.walletHost');
			$walletKey = config('services.extend.walletKey');

			$requestUrl = $walletHost.'/api/wallet/addTrade';
			$walletData = array();
			$walletData['wCode'] = $walletKey;
			$walletData['uId'] = $userInfo['uCode'];
			$walletData['wtType'] = 'charge' ;
			$walletData['wtMoney'] = $aoInfo->aoPay * $scale;
			$walletData['wtObj'] = 'agency_order';
			$walletData['wtObjId'] = $aoId;
			$walletData['wtCustomInfo'] = '';
			$walletData['wtMemo'] = '';
			$addressInfo = $aoInfo->AgencyAddress()->first();
			if ($aoInfo->aoType == 'shop') {
			    $aoTakeInfo = json_decode($aoInfo->aoTakeInfo, true);
			    $wtAbstract = $aoTakeInfo['user_name'] . $aoTakeInfo['cellphone'] . $aoTakeInfo['address'];
            } else {
                $wtAbstract = $addressInfo->csName.'-'.$addressInfo->ssName.'-'.$addressInfo->aaAddress;
            }
			$walletData['wtAbstract'] = $wtAbstract;
			$walletData['wtCode'] = $aoInfo->aoCode;

			$Functions = new Functions();
			$accountInfo = $Functions->Post($requestUrl, $walletData);

			if ($aoInfo->aoType == 'shop'){
                $aoTakeInfo = json_decode($aoInfo->aoTakeInfo, true);
                // 店铺账单处理
                $Functions->Get(env("SHOP_HOST_API") . "/api/schoolTransport/order/orderFinish?order_sn=" . $aoInfo['order_sn']);
				// 是否是虚拟店铺
				$isVirtual = $aoTakeInfo['is_virtual'];
				if ($isVirtual){
					$goodsPrice = $aoTakeInfo['goods'];
					$goodsName = $aoTakeInfo['goods_name'];
					$walletData = array();
					$walletData['wCode'] = $walletKey;
					$walletData['uId'] = $userInfo['uCode'];
					$walletData['wtType'] = 'charge' ;
					$walletData['wtMoney'] = $goodsPrice;
					$walletData['wtObj'] = 'agency_order_goods';
					$walletData['wtObjId'] = $aoId;
					$walletData['wtCustomInfo'] = '';
					$walletData['wtMemo'] = '商品代买转账';
					$addressInfo = $aoInfo->AgencyAddress()->first();
//					$wtAbstract = $addressInfo->csName.'-'.$addressInfo->ssName.'-'.$addressInfo->aaAddress.'-'.$goodsName;
                    $wtAbstract = $aoTakeInfo['address'].'-'.$goodsName;
					$walletData['wtAbstract'] = $wtAbstract;
					$walletData['wtCode'] = $aoInfo->aoCode;

					$accountInfo = $Functions->Post($requestUrl, $walletData);
				}
			}

		}

		return $this->returnMsg(1, 'OK');
	}

	// 获取接单学校下拉框
	public function getKnightSchoolList($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$AgencyAddress = new AgencyAddress();
		$nameList = $AgencyAddress->where('uId', $userInfo['uCode'])->pluck('csName');
		$idList = $AgencyAddress->where('uId', $userInfo['uCode'])->pluck('csId');

		$returnData = array();
		$returnData['nameList'] = $nameList;
		$returnData['idList'] = $idList;
		return $this->returnMsg(1, 'OK', $returnData);
	}

	// 提交指定送货地址
	public function assignAddress(Request $request){

		$token = $request->token;
		$ssIds = $request->ssIds;

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);
		if ($knightInfo->klLevel >= 3){
			return $this->returnMsg(0, '对不起，您当前的骑士等级未开发此功能');
		}

		$ssIdArray = explode(",", $ssIds);

		$addressList = $knightInfo->AskAddress()->get();
		foreach($addressList as $addressInfo){
			$addressInfo->delete();
		}
		foreach($ssIdArray as $ssId){
			$AskAddress = new AskAddress();
			$AskAddress->kId = $knightInfo->kId;
			$AskAddress->ssId = $ssId;
			$AskAddress->save();
		}

		return $this->returnMsg(1, 'OK');
	}

	// 获取可选时间段列表
	public function getScheduleList($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$outColumn = ['ksId', 'ksTimeBucket', 'ksAllowMax', 'ksCurrent'];
		$scheduleList = DB::table('knight_schedule')->select($outColumn)->get();
		$hourList = DB::table('knight_hour')->where('kId', $knightInfo->kId)->get();

		$returnList = array();
		foreach($scheduleList as $scheduleInfo){
			$isMust = 0;
			$scheduleInfo->current = 0;
			foreach($hourList as $hourInfo){
				if ($scheduleInfo->ksId == $hourInfo->ksId){
					if ($hourInfo->khIsMust){
						$isMust = 1;
					}
					$scheduleInfo->current = 1;
				}
			}
			$scheduleInfo->isMust = $isMust;
			array_push($returnList, $scheduleInfo);
		}

		return $this->returnMsg(1, 'OK', $returnList);
	}

	// 设置任务时间段
	public function setHour(Request $request){

		$token = $request->token;
		$ksIds = $request->ksIds;

		$userInfo = $this->getUserInfoFromToken($token);

		$Knight = new Knight();
//		$knightInfo = $Knight->where('uId', $userInfo['uCode'])->first();
		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$ksIdMustList = DB::table('knight_hour')->where('kId', $knightInfo->kId)->where('khIsMust', 1)->pluck('ksId');

		try{
			DB::beginTransaction();

			DB::table('knight_hour')->where('kId', $knightInfo->kId)->delete();
			$ksIdArray = explode(',', $ksIds);
			foreach($ksIdArray as $ksId){
				$isMust = 0;
				foreach($ksIdMustList as $mustKsId){
					if ($ksId == $mustKsId){
						$isMust = 1;
						break;
					}
				}
				if ($ksId){
					DB::table('knight_hour')->insert(
					    ['kId' => $knightInfo->kId, 'ksId' => $ksId, 'khIsMust' => $isMust, 'createDay' => date("Y-m-d")]
					);
				}
			}

			DB::commit();
		} catch (Exception $e){
			DB::rollBack();
			return $this->returnMsg(0, '提交失败，系统错误');
		}

		return $this->returnMsg(1, 'OK');
	}

	// 每日自动生成骑士任务
	public function autoPublishTask(){
		$today = date("Y-m-d");

		// 保底代
		$level2KnightList = DB::table('knight')
						->select(['knight.kId', 'knight.csId', 'knight.klId', 'knight_level.klTargetNum', 'knight_level.klLevel'])
						->leftJoin('knight_level', function ($leftJoin) {
					        $leftJoin->on('knight.csId', '=', 'knight_level.csId')
					        		->on('knight.klId', '=', 'knight_level.klId');
					    })
						->where('kStatus', 1)
						->where('knight.klId', 2)
						->get();

		foreach($level2KnightList as $knightInfo){
			DB::table('knight_task')
				->where('kId', $knightInfo->kId)
				->where('ktDay', $today)
				->delete();

			DB::table('knight_task')->insert([
				'kId' => $knightInfo->kId,
				'csId' => $knightInfo->csId,
				'klId' => $knightInfo->klId,
				'klLevel' => $knightInfo->klLevel,
				'ktDay' => $today,
				'klTargetNum' => $knightInfo->klTargetNum,
			]);
		}

		// 钟点代
		$level3KnightList = DB::table('knight')
						->select(['knight.kId', 'knight.csId', 'knight.klId', 'knight_level.klTargetNum', 'knight_level.klLevel'])
						->leftJoin('knight_level', function ($leftJoin) {
					        $leftJoin->on('knight.csId', '=', 'knight_level.csId')
					        		->on('knight.klId', '=', 'knight_level.klId');
					    })
						->where('kStatus', 1)
						->where('knight.klId', 3)
						->get();

		foreach($level3KnightList as $knightInfo){
			DB::table('knight_task')
				->where('kId', $knightInfo->kId)
				->where('ktDay', $today)
				->delete();

			$hourList =  DB::table('knight_hour')
							->select(['knight_hour.*', 'knight_schedule.*'])
							->leftJoin('knight_schedule', 'knight_hour.ksId', '=', 'knight_schedule.ksId')
							->where('kId', $knightInfo->kId)
							->get();

			foreach($hourList as $hourInfo){
				DB::table('knight_task')->insert([
					'kId' => $knightInfo->kId,
					'csId' => $knightInfo->csId,
					'klId' => $knightInfo->klId,
					'klLevel' => $knightInfo->klLevel,
					'ksId' => $hourInfo->ksId,
					'ksTimeBucket' => $hourInfo->ksTimeBucket,
					'ktDay' => $today,
				]);
			}
		}

		//全职代
		$level4KnightList = DB::table('knight')
						->select(['knight.kId', 'knight.csId', 'knight.klId', 'knight_level.klTargetNum', 'knight_level.klLevel'])
						->leftJoin('knight_level', function ($leftJoin) {
					        $leftJoin->on('knight.csId', '=', 'knight_level.csId')
					        		->on('knight.klId', '=', 'knight_level.klId');
					    })
						->where('kStatus', 1)
						->where('knight.klId', 4)
						->get();

		foreach($level4KnightList as $knightInfo){
			DB::table('knight_task')
				->where('kId', $knightInfo->kId)
				->where('ktDay', $today)
				->delete();

			$hourList =  DB::table('knight_hour')
							->select(['knight_hour.*', 'knight_schedule.*'])
							->leftJoin('knight_schedule', 'knight_hour.ksId', '=', 'knight_schedule.ksId')
							->where('kId', $knightInfo->kId)
							->get();
			foreach($hourList as $hourInfo){
				DB::table('knight_task')->insert([
					'kId' => $knightInfo->kId,
					'csId' => $knightInfo->csId,
					'klId' => $knightInfo->klId,
					'klLevel' => $knightInfo->klLevel,
					'ksId' => $hourInfo->ksId,
					'ksTimeBucket' => $hourInfo->ksTimeBucket,
					'ktDay' => $today,
				]);
			}
		}

		echo 'OK';
	}

	// 获取骑士页所需信息
	public function getKnightPageInfo($token){

		$userInfo = $this->getUserInfoFromToken($token);

		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		// 获取未完成订单数
		$AgencyOrder = new AgencyOrder();
		$num = $AgencyOrder->getToDoOrderNum($knightInfo->kId);

		$pageInfo = array();
		$pageInfo['knight'] = $knightInfo;
		$pageInfo['toDoNum'] = $num;

		return $this->returnMsg(1, 'OK', $pageInfo);
	}

	// 获取骑士未完成订单数
	public function getToDoOrderNum($token){

		$userInfo = $this->getUserInfoFromToken($token);
		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		// 获取未完成订单数
		$AgencyOrder = new AgencyOrder();
		$num = $AgencyOrder->getToDoOrderNum($knightInfo->kId);

		return $this->returnMsg(1, 'OK', $num);
	}

	// 设置骑士信息
	public function setKnightInfo(Request $request){

		$token = $request->token;
		$kAutoTask = $request->autoTask;
		if ($kAutoTask != 1){
			$kAutoTask = 0;
		}

		$userInfo = $this->getUserInfoFromToken($token);
		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$Knight = new Knight();
		$Knight->setInfo($knightInfo->kId, $kAutoTask);

		return $this->returnMsg(1, 'OK');
	}

	// 获取学校地点列表
	public function getSchoolSitList($token, $csId){

		$userInfo = $this->getUserInfoFromToken($token);
		$knightInfo = $this->getKnightInfo($userInfo['uCode']);

		$schoolList = DB::table('school_site')
					->selectRaw('school_site.ssId, school_site.ssName')
					->where('csId', $csId)
					->where('ssEnable', 1)
					->get();

		$setList = DB::table('knight_ask_address')
					->where('kId', $knightInfo->kId)
					->get();

		$returnData = array();
		foreach($schoolList as $siteInfo){
			$isChoose = 0;
			foreach($setList as $setInfo){
				if ($siteInfo->ssId == $setInfo->ssId){
					$isChoose = 1;
					break;
				}
			}
			$siteInfo->isChoose = $isChoose;
			array_push($returnData, $siteInfo);
		}
		return $this->returnMsg(1, 'OK', $returnData);
	}

	// 获取当前在线骑士人数
    public function getOnlineNum($csId, $showDetail=false){

    	return $this->returnMsg(1, '寒假喽，3月1日开始运营', -99);
    	// 获取校园经理数量
    	$managerList = DB::table('school_manager')->where('csId', $csId)->get();

    	if (count($managerList) == 0){
//  		return -1; // 尚未开通该学校服务
			return $this->returnMsg(1, '尚未开通该校区服务', -1);
    	}

    	$nowTime = (int)date('His', time());
    	if ($nowTime > 180000){
//  		return -2; // 第二天服务
			return $this->returnMsg(1, '第二日配送', -2);
    	}
    	if ($nowTime < 80000){
//  		return -3; // 8点后服务
			return $this->returnMsg(1, '8点开始配送', -3);
    	}

    	// 获取自动接单骑士数量
    	$Knight = new Knight();
    	$knightOnlineList = $Knight->getOnlineList($csId);

    	$orderIndex = new orderIndex();

    	// 获取值班骑士列表
    	$getNowKsid = $orderIndex->getNowKsid();
    	$onDutyList = DB::table('knight_hour')
    					->leftJoin('knight', 'knight_hour.kId', '=', 'knight.kId')
    					->where('knight.csId', $csId)
    					->where('ksId', $getNowKsid)
    					->get();

    	$servicingKnightList = array();
    	// 获取校园经理列表
    	foreach($managerList as $managerInfo){
    		array_push($servicingKnightList, $managerInfo->kId);
    	}
    	// 获取当前在线骑士
    	foreach($knightOnlineList as $knightInfo){
    		array_push($servicingKnightList, $knightInfo->kId);
    	}
    	// 获取当前值班骑士
    	foreach($onDutyList as $knightInfo){
    		array_push($servicingKnightList, $knightInfo->kId);
    	}

    	$resultList = array_unique($servicingKnightList);
//		print_r($resultList);exit;
		if ($showDetail){
			$uIdArray = $Knight->whereIn('kId', $resultList)->pluck('uId');
			$returnList = array();

			foreach ($uIdArray as $uId){
				$knightUserInfo = $this->getUserInfoFromUid($uId, true);
				array_push($returnList, $knightUserInfo);
			}
			return $this->returnMsg(1, 'OK', $returnList);
		}else{
			return $this->returnMsg(1, 'OK', $resultList);
		}
    }
}
